<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="地区" prop="areaId">
        <el-cascader v-model="queryParams.areaId" :options="areaOptions"
          :props="{ value: 'id', label: 'label', children: 'children', emitPath: false }" placeholder="请选择地区" clearable
          filterable :show-all-levels="false" />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['basic:station:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['basic:station:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['basic:station:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
          v-hasPermi="['basic:station:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['basic:station:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30" align="center" fixed="left" />
      <el-table-column label="地区" align="left" prop="areaName" />
      <el-table-column label="名称" align="left" prop="name" />
      <el-table-column label="备注" align="left" prop="remark" />
      <el-table-column label="经度" align="left" prop="longitude" />
      <el-table-column label="纬度" align="left" prop="latitude" />
      <el-table-column label="方位角" align="center" prop="directionAngle" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_data_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['basic:station:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['basic:station:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改站点对话框 -->
    <el-dialog :title="title" v-model="open" width="60%" append-to-body>
      <el-form ref="stationRef" :model="form" :rules="rules" label-width="55px">
        <el-row>
          <!-- 站点表单 -->
          <el-col :span="10" style="padding-right: 5px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="地区" prop="areaId">
                  <el-cascader v-model="form.areaId" :options="areaOptions"
                    :props="{ value: 'id', label: 'label', children: 'children', emitPath: false }" placeholder="请选择地区"
                    filterable :show-all-levels="false" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-select v-model="form.status">
                    <el-option v-for="dict in sys_data_status" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="经度" prop="longitude">
                  <el-input v-model="form.longitude" placeholder="请输入经度" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纬度" prop="latitude">
                  <el-input v-model="form.latitude" placeholder="请输入纬度" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="方位角" prop="directionAngle">
                  <el-input v-model="form.directionAngle" placeholder="请输入方位角" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="justify-content: right;">
              <div style="padding-top: 30px;">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
              </div>
            </el-row>
          </el-col>
          <!-- poi搜索地图 -->
          <el-col :span="14" style="padding-left: 5px">
            <mapPoi :containerId="'stationContainer'" ref="mapPoiRef" @emitLngLat="listenLngLat" />
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" action="#" :http-request="httpRequest"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag :data="upload.form">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <el-form :model="upload.form" ref="uploadForm" label-width="100px">
              <el-form-item label="地区" :rules="{ required: true, message: '地区不能为空', trigger: 'change' }" prop="areaId">
                <el-cascader v-model="upload.form.areaId" :options="areaOptions"
                  :props="{ value: 'id', label: 'label', children: 'children', emitPath: false }" placeholder="请选择地区"
                  filterable :show-all-levels="false" />
              </el-form-item>
              <div class="el-upload__tip">
                <el-checkbox v-model="upload.form.updateSupport" label="是否更新已经存在的数据" />
              </div>
            </el-form>
            <br />
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Station">
import { getToken } from "@/utils/auth"
import { listStation, getStation, delStation, addStation, updateStation } from "@/api/basic/station";
import { areaTreeSelect } from "@/api/basic/area";
import mapPoi from "./components/mapPoi";
import { nextTick } from "vue";

const { proxy } = getCurrentInstance();
const { sys_data_status } = proxy.useDict('sys_data_status');

const stationList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const areaOptions = ref([])

/** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  form: {
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    areaId: undefined,
  },
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: "basic/route/import/data"
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    areaId: undefined,
    name: undefined,
    status: undefined,
  },
  rules: {
    areaId: [
      { required: true, message: "地区不能为空", trigger: "change" }
    ],
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    longitude: [
      { required: true, message: "经度不能为空", trigger: "blur" }
    ],
    latitude: [
      { required: true, message: "纬度不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询地区下拉树结构 */
function getAreaTree() {
  areaTreeSelect().then(response => {
    areaOptions.value = response.data;
  })
}

/** 查询站点列表 */
function getList() {
  loading.value = true;
  listStation(queryParams.value).then(response => {
    stationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    areaId: null,
    name: null,
    longitude: null,
    latitude: null,
    directionAngle: null,
    remark: null,
    status: '0',
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("stationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 监听赋值表单经纬度 */
function listenLngLat(e) {
  form.value.longitude = e.longitude
  form.value.latitude = e.latitude
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加站点";

  nextTick(() => {
    proxy.$refs["mapPoiRef"].newMap();
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getStation(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改站点";

    nextTick(() => {
      let params = {
        name: form.value.name,
        areaName: form.value.areaName,
        longitude: form.value.longitude,
        latitude: form.value.latitude,
      }
      proxy.$refs["mapPoiRef"].newMap(params)
    })
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["stationRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateStation(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addStation(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除站点编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delStation(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = '站点导入';
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("basic/station/import/template", {
  }, `station_template_${new Date().getTime()}.xlsx`);
};

/** 文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getHostRoute();
  getList();
};
function httpRequest(data) {
  // 封装FormData对象
  data.data[data.filename] = data.file
  upload.open = false;
  upload.isUploading = false;
  proxy.importFile(upload.url, data.data).then(res => {
    proxy.$refs["uploadRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + res.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  }).catch(err => {
    proxy.$refs["uploadRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + err + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  })
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadForm"].validate((valid) => {
    if (valid) {
      proxy.$refs["uploadRef"].submit();
    } else {
      console.log('error submit!!');
      return false;
    }
  });
};

/** 导出按钮操作 */
function handleExport() {
  proxy.download('basic/station/export', {
    ...queryParams.value
  }, `station_${new Date().getTime()}.xlsx`)
}

getAreaTree();

getList();
</script>